package client.functionalities;

import javax.microedition.rms.*;

import client.screen.ConfigurationScreen;
import client.screen.Screen;

public class ConfigurationFunctionality extends LocalFunctionality {
	private static final String SET_USER = "Login";
	private static final String SET_PASS = "Password";
	private RecordStore recordStore;
	private ConfigurationScreen confScreen;
	
	public ConfigurationFunctionality(Screen s) {
		super();
		this.confScreen = (ConfigurationScreen) s;
	}

	public void run() {
		try {
			this.save();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
	}
	
	public void setFields() {
		try {
			this.setField(ConfigurationFunctionality.SET_USER, "User");
			this.setField(ConfigurationFunctionality.SET_PASS, "Pass");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void save() {
		try {
			this.cleanRecords();
			this.saveOnRecordStore("Login", this.confScreen.getUser());
			this.saveOnRecordStore("Password", this.confScreen.getPass());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void saveOnRecordStore(String recordStoreString, String value) {
		byte[] b = value.getBytes();
		
		try {
			this.recordStore = RecordStore.openRecordStore(recordStoreString, true);
			this.recordStore.addRecord(b, 0, b.length);
			this.recordStore.closeRecordStore();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void cleanRecords() {
		try {
			RecordStore.deleteRecordStore("Login");
			RecordStore.deleteRecordStore("Password");
		} catch (RecordStoreNotFoundException e) {
			e.printStackTrace();
		} catch (RecordStoreException e) {
			e.printStackTrace();
		}
	}
	
	private void setField(String recordStoreString, String defaultString) throws Exception {
		this.recordStore = RecordStore.openRecordStore(recordStoreString, true);
		
		if (this.recordStore.getNumRecords() != 1) {
			this.confScreen.setUser(defaultString);
		}
		else {
			RecordEnumeration re = this.recordStore.enumerateRecords(null, null, true);
			if (re.numRecords() != 1) {
				this.confScreen.setUser(defaultString);
			}
			else {
				while (re.hasNextElement()) {
					String s = new String(re.nextRecord());
					if (recordStoreString == ConfigurationFunctionality.SET_USER)
						this.confScreen.setUser( (s != null) ? s : "");
					else 
						this.confScreen.setPassword( (s != null) ? s : "");
				}
			}
		}
		
		this.recordStore.closeRecordStore();
	}
	
}

